<template>
  <div class="source-list-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">新闻源管理</h1>
        </div>
        <el-button type="primary" @click="handleAdd" class="w-[100px]">
          添加新闻源
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="mb-6" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="新闻源名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入新闻源名称" 
            clearable
            style="width: 180px"
          ></el-input>
        </el-form-item>
        <el-form-item label="新闻源代码">
          <el-input 
            v-model="searchForm.code" 
            placeholder="请输入新闻源代码" 
            clearable
            style="width: 150px"
          ></el-input>
        </el-form-item>
        <el-form-item label="区域">
          <el-select 
            v-model="searchForm.regionId" 
            placeholder="全部区域" 
            clearable
            style="width: 140px"
          >
            <el-option 
              v-for="region in regionOptions" 
              :key="region.id" 
              :label="region.name" 
              :value="region.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="全部状态" 
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="searchForm.sortField" placeholder="排序字段" style="width: 120px">
            <el-option label="ID" value="id"></el-option>
            <el-option label="名称" value="name"></el-option>
            <el-option label="代码" value="code"></el-option>
            <el-option label="排序" value="sortOrder"></el-option>
            <el-option label="创建时间" value="createdAt"></el-option>
            <el-option label="修改时间" value="updatedAt"></el-option>
          </el-select>
          <el-select v-model="searchForm.sortOrder" placeholder="排序方向" style="width: 100px; margin-left: 8px">
            <el-option label="升序" value="asc"></el-option>
            <el-option label="降序" value="desc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">新闻源列表</div>
          <div class="flex space-x-2">
            <el-button size="small" @click="handleRefresh">刷新</el-button>
            <el-button 
              size="small" 
              type="danger" 
              :disabled="!selectedSources.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- 新闻源表格 -->
        <el-table
          :data="sourceList"
          style="width: 100%"
          border
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="新闻源名称" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div class="flex items-center">
                <div 
                  class="w-3 h-3 rounded-full mr-3 flex-shrink-0"
                  :style="{ backgroundColor: getSourceColor(scope.row.code) }"
                ></div>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="新闻源代码" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="homepage" label="主页链接" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <a :href="scope.row.homepage" target="_blank" class="text-blue-500 hover:underline">
                {{ scope.row.homepage }}
              </a>
            </template>
          </el-table-column>
          <el-table-column prop="regionName" label="所属区域" width="100" show-overflow-tooltip>
            <template #default="scope">
              <el-tag size="small" type="info">{{ scope.row.regionName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sortOrder" label="排序" width="100" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                size="small" 
                :type="scope.row.status === 1 ? 'success' : 'danger'"
              >
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="updatedAt" label="修改时间" min-width="180">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.updatedAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button size="small" text @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                size="small" 
                text 
                :type="scope.row.status === 1 ? 'warning' : 'success'" 
                @click="toggleStatus(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger" 
                @click="deleteSource(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="flex justify-between items-center mt-6">
          <div class="text-sm text-gray-500">
            共 {{ total }} 条记录，当前第 {{ searchForm.pageNum }} 页
          </div>
          <el-pagination
            v-model:current-page="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="7"
            prev-text="上一页"
            next-text="下一页"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { sourceAPI, regionAPI } from '~/services/api'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

// 数据加载状态
const loading = ref(false)

// 新闻源列表数据
const sourceList = ref([])

// 区域选项
const regionOptions = ref([])

// 分页相关
const total = ref(0)

// 选中的新闻源
const selectedSources = ref([])

const router = useRouter()

// 搜索表单
const searchForm = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  code: '',
  regionId: null,
  status: null,
  sortField: 'id',
  sortOrder: 'desc'
})

// 加载新闻源数据
const loadSources = async () => {
  try {
    loading.value = true
    
    // 调用后端API获取新闻源列表
    const result = await sourceAPI.getSourceList(searchForm.value)
    
    if (result.code === 200) {
      sourceList.value = Array.isArray(result.data) ? result.data : []
      total.value = result.total || 0
    } else {
      ElMessage.error(result.message || '加载新闻源失败')
      sourceList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载新闻源失败:', error)
    ElMessage.error('加载新闻源失败')
    sourceList.value = []
  } finally {
    loading.value = false
  }
}

// 加载区域选项
const loadRegionOptions = async () => {
  try {
    const result = await regionAPI.getAllRegions()
    if (result.code === 200) {
      regionOptions.value = result.data || []
    }
  } catch (error) {
    console.error('加载区域选项失败:', error)
    ElMessage.error('加载区域选项失败')
  }
}

// 搜索处理
const handleSearch = () => {
  searchForm.value.pageNum = 1
  loadSources()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    code: '',
    regionId: null,
    status: null,
    sortField: 'id',
    sortOrder: 'desc'
  }
  loadSources()
}

// 刷新数据
const handleRefresh = async () => {
  try {
    await loadSources()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  searchForm.value.pageSize = newSize
  searchForm.value.pageNum = 1
  loadSources()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  searchForm.value.pageNum = newPage
  loadSources()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedSources.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedSources.value.length === 0) {
    ElMessage.warning('请选择要删除的新闻源')
    return
  }
  
  try {
    const sourceNames = selectedSources.value.map(item => item.name).join('、')
    
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedSources.value.length} 个新闻源吗？\n${sourceNames}`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const ids = selectedSources.value.map(item => item.id)
    
    // 调用后端API批量删除新闻源
    const result = await sourceAPI.batchDeleteSources(ids)
    
    if (result.code === 200) {
      ElMessage.success('批量删除新闻源成功')
      selectedSources.value = []
      loadSources()
    } else {
      ElMessage.error(result.message || '批量删除新闻源失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除新闻源失败:', error)
      ElMessage.error('批量删除新闻源失败，请重试')
    }
  }
}

// 添加新闻源
const handleAdd = () => {
  router.push('/admin/source/add')
}

// 编辑新闻源
const handleEdit = (row) => {
  router.push(`/admin/source/edit/${row.id}`)
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${statusText}「${row.name}」新闻源吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用后端API更新状态
    const result = await sourceAPI.updateSourceStatus(row.id, newStatus)
    
    if (result.code === 200) {
      // 更新本地数据
      row.status = newStatus
      ElMessage.success(`已${statusText}「${row.name}」新闻源`)
    } else {
      ElMessage.error(result.message || '状态切换失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      ElMessage.error('状态切换失败，请重试')
    }
  }
}

// 删除新闻源
const deleteSource = async (id) => {
  try {
    const source = sourceList.value.find(item => item.id === id)
    
    await ElMessageBox.confirm(
      `确定要删除「${source?.name ?? ''}」新闻源吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用后端API删除新闻源
    const result = await sourceAPI.deleteSource(id)
    
    if (result.code === 200) {
      ElMessage.success('删除新闻源成功')
      loadSources()
    } else {
      ElMessage.error(result.message || '删除新闻源失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除新闻源失败:', error)
      ElMessage.error('删除新闻源失败，请重试')
    }
  }
}

// 根据新闻源代码生成颜色
const getSourceColor = (code) => {
  if (!code) return '#6b7280'
  
  // 预定义一些常用新闻源的颜色
  const colorMap = {
    'xinhua': '#ef4444', // 红色 - 新华网
    'people': '#3b82f6', // 蓝色 - 人民网
    'cctv': '#f59e0b', // 黄色 - 央视网
    'chinadaily': '#10b981', // 绿色 - 中国日报
    'bbc': '#8b5cf6', // 紫色 - BBC
    'cnn': '#06b6d4', // 青色 - CNN
    'reuters': '#f97316', // 橙色 - 路透社
    'nikkei': '#84cc16', // 青绿色 - 日本经济新闻
  }
  
  // 如果代码匹配预定义颜色，使用预定义颜色
  if (colorMap[code]) {
    return colorMap[code]
  }
  
  // 否则根据代码生成随机但一致的颜色
  const colors = [
    '#ef4444', '#f97316', '#f59e0b', '#84cc16', '#10b981',
    '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899', '#f43f5e',
    '#7c3aed', '#1d4ed8', '#059669', '#dc2626', '#991b1b'
  ]
  
  // 使用代码的字符总和来确保相同代码总是得到相同颜色
  const hash = code.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[hash % colors.length]
}

// 时间格式化
const formatDateTime = (val) => {
  if (!val) return '-'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}

// 组件初始化
onMounted(() => {
  loadRegionOptions()
  loadSources()
})
</script>

<style scoped>
.source-list-page {
  @apply w-full;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light) !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
  border-radius: 8px;
  overflow: hidden;
}


:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

</style>
